/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * LocalizarCliente.java
 *
 * Created on 26/04/2011, 00:21:41
 */
package localizarEditar;

import Classe.BD;
import Classe.Validacao;
import editar.EditarCliente;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import javax.swing.text.MaskFormatter;

/**
 *
 * @author gladson
 */
public class LocalizarCliente extends Validacao {

    /** Creates new form LocalizarCliente */
    public LocalizarCliente() {
        initComponents();
        this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
        StxtOpcLoc.setEnabled(false);
    }
    String Selecao;

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        buttonGroupEditarCliente = new javax.swing.ButtonGroup();
        jPanel1 = new javax.swing.JPanel();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tabela = new javax.swing.JTable();
        jPanel3 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        cbSelecaoCli = new javax.swing.JComboBox();
        StxtOpcLoc = new javax.swing.JFormattedTextField();
        jButtonPesquisar = new javax.swing.JButton();
        jPanel4 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        ItxtIdCliente = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setResizable(false);

        jPanel1.setBackground(new java.awt.Color(255, 255, 255));
        jPanel1.setPreferredSize(new java.awt.Dimension(800, 600));

        jPanel2.setBackground(new java.awt.Color(255, 255, 255));
        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(""));

        tabela.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Data Cadastro", "Código", "Nome", "CPF", "RG", "Data de Nascimento"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.Integer.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(tabela);

        jPanel3.setBackground(new java.awt.Color(255, 255, 255));
        jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Localizar Cliente", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Arial", 1, 12))); // NOI18N

        jLabel1.setFont(new java.awt.Font("Arial", 1, 11));
        jLabel1.setText("Localizar por:");

        cbSelecaoCli.setModel(new javax.swing.DefaultComboBoxModel(new String[] {
            "",
            "Data Cadastro",
            "Nome",
            "CPF",
            "RG"}));
cbSelecaoCli.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));
cbSelecaoCli.addItemListener(new java.awt.event.ItemListener() {
    public void itemStateChanged(java.awt.event.ItemEvent evt) {
        cbSelecaoCliItemStateChanged(evt);
    }
    });

    StxtOpcLoc.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));

    jButtonPesquisar.setText("Pesquisar");
    jButtonPesquisar.setToolTipText("Pesquisar");
    jButtonPesquisar.setBorder(javax.swing.BorderFactory.createCompoundBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED), javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED)));
    jButtonPesquisar.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButtonPesquisarActionPerformed(evt);
        }
    });

    javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
    jPanel3.setLayout(jPanel3Layout);
    jPanel3Layout.setHorizontalGroup(
        jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(jPanel3Layout.createSequentialGroup()
            .addContainerGap()
            .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                .addComponent(StxtOpcLoc, javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel3Layout.createSequentialGroup()
                    .addComponent(jLabel1)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(cbSelecaoCli, javax.swing.GroupLayout.PREFERRED_SIZE, 207, javax.swing.GroupLayout.PREFERRED_SIZE)))
            .addGap(18, 18, 18)
            .addComponent(jButtonPesquisar)
            .addContainerGap(368, Short.MAX_VALUE))
    );
    jPanel3Layout.setVerticalGroup(
        jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(jPanel3Layout.createSequentialGroup()
            .addContainerGap()
            .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(jLabel1)
                .addComponent(cbSelecaoCli, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(StxtOpcLoc, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jButtonPesquisar))
            .addContainerGap())
    );

    jPanel4.setBackground(new java.awt.Color(255, 255, 255));
    jPanel4.setBorder(javax.swing.BorderFactory.createTitledBorder(""));

    jLabel2.setFont(new java.awt.Font("Arial", 1, 11));
    jLabel2.setText("Código do Cliente: ");

    ItxtIdCliente.setBorder(javax.swing.BorderFactory.createCompoundBorder(javax.swing.BorderFactory.createEtchedBorder(), javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED)));

    jButton1.setText("Editar Cliente");
    jButton1.setToolTipText("Editar Cliente");
    jButton1.setBorder(javax.swing.BorderFactory.createCompoundBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED), javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED)));
    jButton1.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton1ActionPerformed(evt);
        }
    });

    javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
    jPanel4.setLayout(jPanel4Layout);
    jPanel4Layout.setHorizontalGroup(
        jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(jPanel4Layout.createSequentialGroup()
            .addContainerGap()
            .addComponent(jLabel2)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(ItxtIdCliente, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addGap(18, 18, 18)
            .addComponent(jButton1)
            .addContainerGap(467, Short.MAX_VALUE))
    );
    jPanel4Layout.setVerticalGroup(
        jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(jPanel4Layout.createSequentialGroup()
            .addContainerGap()
            .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(jLabel2)
                .addComponent(ItxtIdCliente, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jButton1))
            .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    );

    jButton2.setText("Sair");
    jButton2.setToolTipText("Sair");
    jButton2.setBorder(javax.swing.BorderFactory.createCompoundBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED), javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED)));
    jButton2.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton2ActionPerformed(evt);
        }
    });

    javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
    jPanel2.setLayout(jPanel2Layout);
    jPanel2Layout.setHorizontalGroup(
        jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
            .addContainerGap()
            .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 748, Short.MAX_VALUE)
                .addComponent(jPanel3, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jPanel4, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jButton2, javax.swing.GroupLayout.Alignment.LEADING))
            .addContainerGap())
    );
    jPanel2Layout.setVerticalGroup(
        jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(jPanel2Layout.createSequentialGroup()
            .addGap(11, 11, 11)
            .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addGap(18, 18, 18)
            .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addGap(18, 18, 18)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 308, Short.MAX_VALUE)
            .addGap(18, 18, 18)
            .addComponent(jButton2)
            .addContainerGap())
    );

    javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
    jPanel1.setLayout(jPanel1Layout);
    jPanel1Layout.setHorizontalGroup(
        jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(jPanel1Layout.createSequentialGroup()
            .addContainerGap()
            .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addContainerGap())
    );
    jPanel1Layout.setVerticalGroup(
        jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(jPanel1Layout.createSequentialGroup()
            .addContainerGap()
            .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addContainerGap())
    );

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 601, Short.MAX_VALUE)
    );

    java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
    setBounds((screenSize.width-808)/2, (screenSize.height-628)/2, 808, 628);
    }// </editor-fold>//GEN-END:initComponents

    private void jButtonPesquisarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonPesquisarActionPerformed
        if (cbSelecaoCli.getSelectedItem().equals("")) {
            JOptionPane.showMessageDialog(rootPane, "Selecione uma opção para consulta!!");
        } else {
            if (validarLocalizador(StxtOpcLoc.getText())) {
                try {

                    String Opcao = ((String) cbSelecaoCli.getSelectedItem());
                    boolean esc = false;

                    if (Opcao.equalsIgnoreCase("Data Cadastro")) {
                        Selecao = "DATA_CADAS_CLIENTE LIKE '%";
                        esc = true;
                    }
                    if (Opcao.equalsIgnoreCase("Nome")) {
                        Selecao = "NOME_CLIENTE LIKE '%";
                        esc = true;
                    }
                    if (Opcao.equalsIgnoreCase("CPF")) {
                        Selecao = "CPF_CLIENTE";
                        esc = false;
                    }
                    if (Opcao.equalsIgnoreCase("RG")) {
                        Selecao = "RG_CLIENTE LIKE '%";
                        esc = true;
                    }

                    String sql = "SELECT * FROM CLIENTE WHERE " + Selecao + "='" + StxtOpcLoc.getText().trim().toUpperCase() + "'";

                    if (esc) {
                        String sql2 = "SELECT * FROM CLIENTE WHERE " + Selecao + "" + StxtOpcLoc.getText().trim().toUpperCase() + "%'";
                        sql = sql2;

                    }

                    BD banco = new BD();
                    ResultSet res = banco.consultar(sql);

                    DefaultTableModel model = (DefaultTableModel) tabela.getModel();
                    model.setNumRows(0);
                    while (res.next()) {
//---------------------------------formatando a data de cadastro---------------------------

                        String data2 = res.getString("DATA_CADAS_CLIENTE");
                        String dtFinalC = "";
                        if (data2 != null) {
                            String dataC = data2.split(" ")[0];  //corta a strin onde tem o espaço
                            String[] vDataC = dataC.split("-");//corta a onde tem "-"
                            String diaC = vDataC[2];
                            String mesC = vDataC[1];
                            String anoC = vDataC[0];
                            dtFinalC = diaC + "/" + mesC + "/" + anoC;
                        }

//---------------------------------fim da formatação da data--------------------------------
//---------------------------------formatando a data de nascimento---------------------------
                        String data1 = res.getString("DATA_NASC_CLIENTE");
                        String dtFinal = "";
                        if (data1 != null) {
                            String data = data1.split(" ")[0];  //corta a strin onde tem o espaço
                            String[] vData = data.split("-");//corta a onde tem "-"
                            String dia = vData[2];
                            String mes = vData[1];
                            String ano = vData[0];
                            dtFinal = dia + "/" + mes + "/" + ano;
                        }

//---------------------------------fim da formatação da data--------------------------------
                        Object[] linha = {
                            dtFinalC,
                            res.getInt("ID_CLIENTE"),
                            res.getString("NOME_CLIENTE"),
                            res.getString("CPF_CLIENTE"),
                            res.getString("RG_CLIENTE"),
                            dtFinal};

                        model.addRow(linha);
                    }


                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

    }//GEN-LAST:event_jButtonPesquisarActionPerformed
    MaskFormatter mascara = new MaskFormatter();
    private void cbSelecaoCliItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_cbSelecaoCliItemStateChanged

        StxtOpcLoc.setEnabled(true);
        if (cbSelecaoCli.getSelectedItem() == "CPF") {
            try {
                mascara.setMask("###.###.###-##");
            } catch (ParseException ex) {
                Logger.getLogger(LocalizarCliente.class.getName()).log(Level.SEVERE, null, ex);
            }
            mascara.setPlaceholderCharacter(' ');
            mascara.install(StxtOpcLoc);
        } else if (cbSelecaoCli.getSelectedItem() == "Data Cadastro") {
            try {
                mascara.setMask("##/##/##");
            } catch (ParseException ex) {
                Logger.getLogger(LocalizarCliente.class.getName()).log(Level.SEVERE, null, ex);
            }
            mascara.setPlaceholderCharacter(' ');
            mascara.install(StxtOpcLoc);
        } else {

            mascara.uninstall();
            StxtOpcLoc.setText("");

        }
    }//GEN-LAST:event_cbSelecaoCliItemStateChanged

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        if (validarNumero(ItxtIdCliente.getText())) {
            int idCliente = Integer.parseInt(ItxtIdCliente.getText());
            try {
                String sqlp = "SELECT * FROM CLIENTE WHERE ID_CLIENTE =" + idCliente;
                BD bd2 = new BD();
                ResultSet r2;
                r2 = bd2.consultar(sqlp);
                if (r2.next()) {
                    EditarCliente editarCli = new EditarCliente();
                    editarCli.inicializar(idCliente);
                    editarCli.setVisible(true);
                    this.dispose();
                } else {
                    JOptionPane.showMessageDialog(rootPane, "Cliente Não encontrado na base de dados");
                    ItxtIdCliente.setText("");
                }

            } catch (ClassNotFoundException ex) {
                Logger.getLogger(LocalizarCliente.class.getName()).log(Level.SEVERE, null, ex);
            } catch (SQLException ex) {
                Logger.getLogger(LocalizarCliente.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        this.dispose();
    }//GEN-LAST:event_jButton2ActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new LocalizarCliente().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField ItxtIdCliente;
    private javax.swing.JFormattedTextField StxtOpcLoc;
    private javax.swing.ButtonGroup buttonGroupEditarCliente;
    private javax.swing.JComboBox cbSelecaoCli;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButtonPesquisar;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable tabela;
    // End of variables declaration//GEN-END:variables
}
